/*******************************************************************************
 * Binground Business Logic                        http://binground.codeplex.com
 *                                              Microsoft Public License (Ms-PL)
 * Authors
 *  - Michael Flanakin  2008-09  http://www.michaelflanakin.com
 *
 * gadget
 *  - pages    : page constants
 *  - host     : host properties/functions
 *  - init     : initialization event
 *  - getImage : gets the current image from bing.com
 ******************************************************************************/

var binground =
{
	/***************************************************************************
	 * binground.pages : standard page names
	 **************************************************************************/
	pages:
	{
		main: 'main.htm',
		flyout: 'flyout.htm'
	},


	/***************************************************************************
	 * binground.properties : standard properties
	 **************************************************************************/
	properties:
	{
		image: "image",
		setImage: function(val) { $.gadget.settings(binground.properties.image, val); return binground.image = val; },
		sync: function() { binground.image = $.gadget.settings(binground.properties.image); }
	},


	//***| properties |*********************************************************

	image: null,
	project: "binground",
	dockedSize: { height: 68, width: 130 },
	undockedSize: { height: 256, width: 483 },
	updateCheckInterval: 24 * 60 * 60 * 1000,  // 24 hours
	refreshInterval: 60 * 1000,  // 60 seconds


	//***| binground.getImage() |****************************************************

	getImage: function() {
		var html = $.ajax({ url:'http://www.bing.com', async:false, cache:false }).responseText;
		var match = html.match(/g_img={url:'[\\\/A-Za-z0-9_\.\-]+'/gm);
		// TODO: Return error image
		if (match.length == 0) { alert('Background image could not be parsed!'); return binground.image; }
		var url = match[0];
		url = url.replace(/\\/g, "/").replace(/\/\//g, "/");
		if (url) { url = url.substring(12, url.length - 1); }
		return binground.properties.setImage("http://bing.com" + url);
	},


	//***| binground.isUpToDate() |**************************************************

	isUpdateAvailable: function() {
		return $.version.isNewer($.gadget.version(), $.codeplex.getDefaultVersion(binground.project));
	},


	//***| binground.init() |********************************************************

	init: function() {
		binground.properties.sync();
		page.init();
	}
};
$(binground.init);
